<template>
  <div class="tit01" data-icon="growth">审计发现问题分布</div>
  <div class="ftechart" ref="chartContainer"></div>
  
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { queuedFetch } from '../utils/queuedRequest.js'

const chartContainer = ref(null)
let chartInstance = null

const apiUrl = '/coolv/edatasource/jdbcmgr.do'
// 仅展示前N个类别，剩余合并为“其他”
const TOP_N = 5

const fetchData = async () => {
  console.debug('[MainIssueDist] 准备请求主要问题分布数据...')
  // 去掉SQL首尾空白，避免DB2解析错误
  const sql = `SELECT
  FIRST_CLASS_NAME,
  PROBLEM1_COUNT,
  PROBLEM2_COUNT,
  PROBLEM3_COUNT,
  TOTAL_COUNT
FROM (
    -- 第 2 层：对聚合结果进行排序和编号
    SELECT
      AGG_DATA.*,
      ROW_NUMBER() OVER (ORDER BY TOTAL_COUNT DESC) AS RN
    FROM (
        -- 第 1 层：执行聚合（GROUP BY）
        SELECT
          FIRST_CLASS_NAME,
          SUM(HIGH_CNT) AS PROBLEM1_COUNT,
          SUM(MID_CNT) AS PROBLEM2_COUNT,
          SUM(LOW_CNT) AS PROBLEM3_COUNT,
          SUM(HIGH_CNT + MID_CNT + LOW_CNT) AS TOTAL_COUNT
        FROM (
            -- 第 0 层：原始数据转换（原 WITH BASE 的内容）
            SELECT
              FIRST_CLASS_NAME,
              CASE WHEN RISK_DEGREE_VALUE IN ('重大', '高') THEN 1 ELSE 0 END AS HIGH_CNT,
              CASE WHEN RISK_DEGREE_VALUE IN ('中') THEN 1 ELSE 0 END AS MID_CNT,
              CASE WHEN RISK_DEGREE_VALUE IN ('低', '低微') THEN 1 ELSE 0 END AS LOW_CNT
            FROM V_PROB_INFO
            WHERE FIRST_CLASS_NAME IS NOT NULL
              AND PROBLEM_DATE IS NOT NULL
        ) AS BASE -- 将原 WITH BASE 的内容作为子查询放在 FROM 后面
        GROUP BY FIRST_CLASS_NAME
    ) AS AGG_DATA -- 聚合结果
) AS RANKED_DATA -- 排序和编号后的结果
WHERE RN <= 50
ORDER BY RN -- 确保输出顺序`.trim()

  // SQL编码：与 amsedb 数据源保持一致
  // 1. URL编码
  let encodedSql = encodeURIComponent(sql)
  // 2. Base64编码
  encodedSql = btoa(encodedSql)

  const formBody = new URLSearchParams()
  formBody.set('action', 'exesql')
  formBody.set('jdbcName', 'DB2')
  formBody.set('enc', 'true')
  formBody.set('sql', encodedSql)
  formBody.set('pageIndex', 'undefined')
  formBody.set('pageSize', '100')
  formBody.set('isSys', 'false')

  // 使用队列化请求
  const res = await queuedFetch(apiUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
    body: formBody.toString()
  }, {
    name: '业务对比数据',
    priority: 3  // 优先级
  })
  const data = await res.json()
  console.debug('[MainIssueDist] 接口返回: isselect=', data?.isselect, 'count=', data?.totalcount)

  const rows = Array.isArray(data?.datas) ? data.datas : []
  const parsed = rows.map((row) => {
    const name = row[0]
    const high = Number(row[1]) || 0
    const mid = Number(row[2]) || 0
    const low = Number(row[3]) || 0
    const total = Number(row[4]) || high + mid + low
    return { name, high, mid, low, total }
  }).sort((a, b) => b.total - a.total)

  const topEntries = parsed.slice(0, TOP_N)

  if (parsed.length > TOP_N) {
    const others = parsed.slice(TOP_N).reduce(
      (acc, cur) => {
        acc.high += cur.high
        acc.mid += cur.mid
        acc.low += cur.low
        acc.total += cur.total
        return acc
      },
      { name: '其他', high: 0, mid: 0, low: 0, total: 0 }
    )
    if (others.total > 0) {
      topEntries.push(others)
    }
  }

  // --- 视觉加权逻辑 ---
  const HIGH_RISK_WEIGHT = 20; // 高风险问题的视觉权重因子
  const MID_RISK_WEIGHT = 2; // 中风险问题的视觉权重因子

  const finalData = topEntries.map(item => {
    const { name, high, mid, low } = item
    const real = { high, mid, low }

    const display = {
      high: high * HIGH_RISK_WEIGHT,
      mid: mid * MID_RISK_WEIGHT,
      low
    }

    return { name, display, real }
  })


  const categories = finalData.map(item => item.name)
  const highSeries = finalData.map(item => ({ value: item.display.high, real: item.real }))
  const midSeries = finalData.map(item => ({ value: item.display.mid, real: item.real }))
  const lowSeries = finalData.map(item => ({ value: item.display.low, real: item.real }))


  console.debug('[MainIssueDist] 处理后分类:', categories)
  console.debug('[MainIssueDist] (加权)高风险数据:', highSeries.map(s => s.value))
  console.debug('[MainIssueDist] (加权)中风险数据:', midSeries.map(s => s.value))
  console.debug('[MainIssueDist] (加权)低风险数据:', lowSeries.map(s => s.value))

  return { categories, highSeries, midSeries, lowSeries }
}

const initChart = async () => {
  if (!chartContainer.value) return
  
  chartInstance = echarts.init(chartContainer.value)

  const { categories, highSeries, midSeries, lowSeries } = await fetchData().catch((e) => {
    console.error('[MainIssueDist] 获取失败:', e)
    return {
      categories: [],
      highSeries: [],
      midSeries: [],
      lowSeries: []
    }
  })

  const fallbackSource = {
    categories: ['信贷业务', '银行卡', '中间业务', '印章管理', '信贷管理', '其他'],
    high: [23, 1, 0, 3, 16, 5],
    mid: [874, 233, 157, 158, 221, 120],
    low: [655, 319, 294, 273, 113, 200]
  }

  const HIGH_RISK_WEIGHT = 20
  const MID_RISK_WEIGHT = 2

  let xData, highData, midData, lowData

  if (categories.length > 0) {
    xData = categories
    highData = highSeries
    midData = midSeries
    lowData = lowSeries
  } else {
    // 兜底数据也按前TOP_N展示，剩余合并为“其他”
    const parsedFallback = fallbackSource.categories.map((name, i) => {
      const real = {
        high: fallbackSource.high[i],
        mid: fallbackSource.mid[i],
        low: fallbackSource.low[i]
      }
      const total = real.high + real.mid + real.low
      return { name, ...real, total }
    }).sort((a, b) => b.total - a.total)

    const topFallback = parsedFallback.slice(0, TOP_N)
    if (parsedFallback.length > TOP_N) {
      const others = parsedFallback.slice(TOP_N).reduce((acc, cur) => {
        acc.high += cur.high
        acc.mid += cur.mid
        acc.low += cur.low
        acc.total += cur.total
        return acc
      }, { name: '其他', high: 0, mid: 0, low: 0, total: 0 })
      if (others.total > 0) topFallback.push(others)
    }

    xData = topFallback.map(d => d.name)
    highData = topFallback.map(d => ({ value: d.high * HIGH_RISK_WEIGHT, real: { high: d.high, mid: d.mid, low: d.low } }))
    midData = topFallback.map(d => ({ value: d.mid * MID_RISK_WEIGHT, real: { high: d.high, mid: d.mid, low: d.low } }))
    lowData = topFallback.map(d => ({ value: d.low, real: { high: d.high, mid: d.mid, low: d.low } }))
  }

  const gradientColors = {
    low: '#3dd598',
    mid: '#f7b731',
    high: '#ff6b6b'
  }

  const option = {
    // 调整颜色顺序以匹配新的序列顺序：低(绿)、中(黄)、高(红)
    color: ['#3dd598', '#f7b731', '#ff6b6b'],
    legend: {
      // 保持图例顺序与视觉直觉一致
      data: ['高风险', '中风险', '低风险'],
      textStyle: { color: '#fff' },
      right: '5%',
      top: '6%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(0,0,0,0.8)',
      textStyle: { color: '#fff' },
      formatter: (params) => {
        const categoryName = params[0].name;
        // 从 params 的第一个系列数据点中获取真实的原始数据
        const realData = params[0].data.real;
        if (!realData) return '数据信息错误';

        const { high, mid, low } = realData;
        const total = high + mid + low;

        const highMarker = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#ff6b6b;"></span>';
        const midMarker = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#f7b731;"></span>';
        const lowMarker = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#3dd598;"></span>';

        return `
          <strong>${categoryName}</strong><br/>
          问题总数: <strong>${total}</strong><br/>
          ${highMarker}高风险: <strong>${high}</strong><br/>
          ${midMarker}中风险: <strong>${mid}</strong><br/>
          ${lowMarker}低风险: <strong>${low}</strong>
        `;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '6%',
      top: '18%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLine: { lineStyle: { color: 'rgba(255,255,255,0.3)' } },
      axisLabel: { color: '#fff', fontSize: 10, interval: 0 }
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: 'rgba(255,255,255,0.3)' } },
      axisLabel: { color: '#fff', fontSize: 10 },
      splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
    },
    series: [
      {
        name: '低风险',
        type: 'bar',
        stack: '总量',
        data: lowData,
        barMaxWidth: 24,
        itemStyle: {
          color: gradientColors.low
        }
      },
      {
        name: '中风险',
        type: 'bar',
        stack: '总量',
        data: midData,
        barMaxWidth: 24,
        itemStyle: {
          color: gradientColors.mid
        }
      },
      {
        name: '高风险',
        type: 'bar',
        stack: '总量',
        data: highData,
        barMaxWidth: 24,
        itemStyle: {
          color: gradientColors.high
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>
